package com.szewec.ps.ui.member;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;

import androidx.databinding.DataBindingUtil;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.alibaba.fastjson.JSONObject;
import com.szewec.ps.R;
import com.szewec.ps.base.BaseActivity;
import com.szewec.ps.base.BaseUrl;
import com.szewec.ps.base.Constants;
import com.szewec.ps.databinding.ActivityMemberSelectBinding;
import com.szewec.ps.model.PresentValue;
import com.szewec.ps.model.project.ProjectListModel;
import com.szewec.ps.model.project.SelectUserModel;
import com.szewec.ps.model.user.RoleFindResult;
import com.szewec.ps.myinterface.IUserInfo;
import com.szewec.ps.myview.toast.bamtoast.BamToast;
import com.szewec.ps.util.OneOffCupboard;
import com.szewec.ps.util.PreferincesContext;
import com.szewec.ps.util.SharedPreferencesUtil;
import com.szewec.ps.util.dialog.LoadingDialog;
import com.szewec.ps.util.okhttp.OkHttp;

import org.jetbrains.annotations.NotNull;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import butterknife.ButterKnife;

import static com.szewec.ps.base.Constants.PRESENT_VALUE;

public class MemberSelectActivity extends BaseActivity {
    public static final String SELECTED_MEMBERS_KEY = "SELECTED_MEMBERS_KEY";

    private ActivityMemberSelectBinding _binding;
    private LoadingDialog loadingDialog;

    private MemberListAdapter _memberListAdapter;
    private List<SelectUserModel> _dataSource = new ArrayList<>();

    private List<? extends IUserInfo> _selectList = new ArrayList<>();

    @Override
    protected void onCreate(Bundle savedInstanceState) {

        super.onCreate(savedInstanceState);
        _binding = DataBindingUtil.setContentView(this, R.layout.activity_member_select);
        ButterKnife.bind(this);
        loadingDialog = LoadingDialog.getInstance(this);

        initData();

        getListDataFromServer();

        LinearLayoutManager manager0 = new LinearLayoutManager(this);
        manager0.setOrientation(LinearLayoutManager.VERTICAL);
        _binding.memberRecyclerView.setLayoutManager(manager0);
        _memberListAdapter = new MemberListAdapter(this);
        _binding.memberRecyclerView.setAdapter(_memberListAdapter);

        _binding.search.setOnClickListener(this::linkToSearchActivity);

        //显示返回按钮
        _binding.titleBar.setLeftLayoutVisibility(View.VISIBLE);
        _binding.titleBar.setLeftLayoutClickListener(this::returnCheck);
        //设置右边按钮
        _binding.titleBar.setRightTextVisibility(View.VISIBLE);
        _binding.titleBar.setRightText("确定");
        _binding.titleBar.setRightLayoutClickListener(this::doSure);
    }

    private void initData(){
        PresentValue<List<? extends IUserInfo>> presentValue = (PresentValue<List<? extends IUserInfo>>) getIntent().getSerializableExtra(Constants.PRESENT_VALUE);
        _selectList = presentValue.getT();
    }

    private void returnCheck(){
        finish();
    }

    private void doSure(){
        Log.i("Member select activity","do sure...");

        List<SelectUserModel> selectedArr = new ArrayList<>();
        for (SelectUserModel model : _dataSource) {
            if (model.getIfSelected()){
                selectedArr.add(model);
            }
        }

        if (selectedArr.size() == 0){
            BamToast.showText(MemberSelectActivity.this, "您还没有选择成员！");
            return;
        }

        /*Intent intent = new Intent();
        PresentValue<List<SelectUserModel>> presentValue = new PresentValue<>(SELECTED_MEMBERS_KEY, selectedArr);
        intent.putExtra(Constants.PRESENT_VALUE, presentValue);
        setResult(RESULT_OK, intent);*/
        setResult(RESULT_OK, new Intent());
        OneOffCupboard.sharedInstance().set(SELECTED_MEMBERS_KEY, selectedArr);

        finish();
    }

    private void linkToSearchActivity(View view) {
        BamToast.showText(MemberSelectActivity.this, "敬请期待！");
        /*startActivity(new Intent(this, MemberSearchActivity.class));*/
    }

    private void getListDataFromServer(){

        //公司id
        String companyId = (String) SharedPreferencesUtil.getData(PreferincesContext.COMPANY_ID,"");
        Log.i("company id is：" , companyId);

        //请求参数设置，请求全部人回来.
        HashMap<String, Object> params = new HashMap<>();
        params.put("companyId",companyId);
        params.put("appId", BaseUrl.APP_ID);
        params.put("pageSize",99999);
        params.put("pageIndex", 1);

        OkHttp.get("/tpms-plan-service/api/roles-management/get-user-by-companyId/", params, loadingDialog, (result -> {
            loadingDialog.close();

            Log.i("member api result is ：" , result);

            RoleFindResult roleFindResult = JSONObject.parseObject(result, RoleFindResult.class);


            List<SelectUserModel> modelList = roleFindResult.getData().getAuthorizedUsers();
            if (modelList != null){

                List<SelectUserModel> sortedList = new ArrayList<>();
                //先转map
                Map<String, Object> map = new HashMap<>();
                for (IUserInfo obj : _selectList){
                    map.put(obj.getUserId(), obj);
                }

                List<SelectUserModel> sList = new ArrayList<>();
                List<SelectUserModel> usList = new ArrayList<>();
                //把已经选择的排序到前面去
                for (SelectUserModel model : modelList){
                    if (map.get(model.getUserId()) != null){
                        model.setIfSelected(true);
                        sList.add(model);
                    }
                    else {
                        model.setIfSelected(false);
                        usList.add(model);
                    }
                }

                sortedList.addAll(sList);
                sortedList.addAll(usList);

                runOnUiThread(() -> {
                    _dataSource = sortedList;
                    _memberListAdapter.notifyDataSetChanged();
                });
            }


        }));
    }

    class MemberListAdapter extends RecyclerView.Adapter<MemberListAdapter.MemberListViewHolder>{

        private Context context;

        public MemberListAdapter(Context context){
            this.context = context;
        }

        @Override
        public int getItemCount() {
            return _dataSource.size();
        }

        @Override//getItemViewType返回行号的化，onCreateViewHolder的viewType就是行号
        public int getItemViewType(int position) {
            return position;
        }

        @NotNull
        @Override
        public MemberListViewHolder onCreateViewHolder(@NotNull ViewGroup parent, int viewType) {
            //获取添加视图
            View contentView = LayoutInflater.from(context).inflate(R.layout.item_member_select_cell, parent, false);
            return new MemberListViewHolder(contentView);
        }


        @Override
        public void onBindViewHolder(@NotNull MemberSelectActivity.MemberListAdapter.MemberListViewHolder viewHolder, int position) {
            SelectUserModel model = _dataSource.get(position);

            viewHolder.memberName.setText(model.getName());
            viewHolder.memberPhone.setText(model.getPhoneNumber());

            if (model.getIfSelected()){
                setSelectedStyle(viewHolder);
            }else {
                setUnselectStyle(viewHolder);
            }

            viewHolder.itemView.setOnClickListener((view)->{
                model.setIfSelected(!model.getIfSelected());

                if (model.getIfSelected()){
                    setSelectedStyle(viewHolder);
                }else {
                    setUnselectStyle(viewHolder);
                }
            });
        }

        private void setUnselectStyle(MemberListViewHolder viewHolder){
            viewHolder.rightIconView.setBackground(getResources().getDrawable(R.drawable.ic_checkbox_passive));
            //viewHolder.rightIconView.setImageDrawable(getResources().getDrawable(R.drawable.ic_checkbox_passive));
        }

        private void setSelectedStyle(MemberListViewHolder viewHolder){
            viewHolder.rightIconView.setBackground(getResources().getDrawable(R.drawable.ic_checkbox_active));
            //viewHolder.rightIconView.setImageDrawable(getResources().getDrawable(R.drawable.ic_checkbox_active));
        }

        //内部类，绑定控件
        class MemberListViewHolder extends RecyclerView.ViewHolder{
            TextView memberName;
            TextView memberPhone;
            ImageView rightIconView;
            public MemberListViewHolder(View itemView) {
                super(itemView);
                memberName = itemView.findViewById(R.id.member_Name);
                memberPhone = itemView.findViewById(R.id.member_Phone);
                rightIconView = itemView.findViewById(R.id.ic_select);
            }
        }
    }
}
